import React from "react";
import { bindActionCreators } from "@reduxjs/toolkit";

import { useAppDispatch } from "../hooks";
import { Actions } from "./actionCreators";

import type { IFetchResponse, IFetchOptions } from "../../types";

export const useFetch = ({ url, options }: IFetchOptions): IFetchResponse => {
  const [isLoading, setLoading] = React.useState(true);
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  const cache = React.useRef({});

  const fetchData = async () => {
    if (cache.current[url]) {
      const data = cache.current[url];
      setResponse(data);
    } else {
      try {
        const response = await fetch(url, options);
        const json = await response.json();
        cache.current[url] = json;
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    }

    setLoading(false);
  };

  React.useEffect(() => {
    fetchData();
  }, [url, options]);

  return { isLoading, response, error };
};

export const useActions = () => {
  const dispatch = useDispatch();

  return bindActionCreators(Actions, dispatch);
};

export const useInput = (initialValue: string) => {
  const [value, setValue] = React.useState(initialValue);

  const onChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    setValue(e.target.value);
  };

  return { value, onChange };
};